//
//  MXFriendslListVC.swift
//  XMPPTest
//
//  Created by 陈学明 on 17/2/9.
//  Copyright © 2017年 muxue. All rights reserved.
//

import UIKit
import XMPPFramework
class MXFriendslListVC: MXBaesVC ,UITableViewDelegate,UITableViewDataSource,XMPPRosterDelegate,RosterListDelegate{
    var tableview:UITableView!
    var appdelegate:AppDelegate!
    
    var xmppRoster:XMPPRoster!
    var rosterField:UITextField!
    var onlineRosters = NSMutableArray()
    var offlineRosters = NSMutableArray()
    var tryRosters = NSMutableArray()
    var SCREEN_W:CGFloat!
    var zheImage:UIImage!
    var zhanImage:UIImage!
    var headers = ["在线好友","离线好友","尝试添加的好友"]
    var status = [false,false,false]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNavItem()
        createUI()
    }
    func createUI() {
        SCREEN_W = UIScreen.main.bounds.size.width
        appdelegate = UIApplication.shared.delegate as! AppDelegate!
        appdelegate.rosterListDelegate = self
        
        zheImage = UIImage(named:"")
        zhanImage = UIImage(named:"")
        
        tableview = UITableView(frame: CGRect.zero, style: .plain)
        view.addSubview(tableview!)
        tableview?.sd_layout()
            .leftSpaceToView(view,0)?
            .topSpaceToView(view,70)?
            .bottomSpaceToView(view,50)?
            .widthRatioToView(view,1.0)
        tableview?.delegate = self
        tableview?.dataSource = self
        tableview?.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "ID")
        
        setUpRoster()
        onlineRosters.removeAllObjects()
        offlineRosters.removeAllObjects()
        tryRosters.removeAllObjects()
        
    }
    
    func setUpNavItem(){
        titleText?.text = "好友列表"
        rigt0?.setTitle("添加", for: .normal)
        rigt0?.rac_signal(for: .touchUpInside).subscribeNext({ (x) in
            
        })
    }
    
    func setUpRoster(){
        if appdelegate.rosterStorage == nil {
            appdelegate.rosterStorage = XMPPRosterCoreDataStorage()
        }
        xmppRoster = XMPPRoster(rosterStorage: appdelegate.rosterStorage)
        //建立关联
        xmppRoster.activate(appdelegate.xmppStream)
        //设置代理
        xmppRoster.addDelegate(self, delegateQueue: appdelegate.queue)
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let arr = section == 0 ? onlineRosters : (section == 1 ? offlineRosters : tryRosters)
        
        return status[section] ? arr.count : 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview?.dequeueReusableCell(withIdentifier: "ID")
        
        let section = indexPath.section
        
        let arr = section == 0 ? onlineRosters : (section == 1 ? offlineRosters : tryRosters)
        
        cell?.textLabel?.text = String(format:"第%02d个好友",indexPath.row)
        cell?.selectionStyle = .none
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 34
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = UIColor.orange
        btn.frame = CGRect(x: 0, y: 0, width: SCREEN_W, height: 34)
        btn.titleLabel?.sd_layout().leftSpaceToView(btn,20)
        btn.setTitle(headers[section], for: UIControlState(rawValue:0))
        btn.setTitleColor(UIColor.black, for: UIControlState(rawValue:0))
        btn.tag = section;
        btn.rac_signal(for: .touchUpInside).subscribeNext { (x) in
               self.status[btn.tag] = !self.status[btn.tag]
            let indexSet = NSIndexSet(index:btn.tag)
            self.tableview.reloadSections(indexSet as IndexSet, with: .automatic)
        }
        return btn;
    }
    //MARK--
    //收到好友信息
    func xmppRoster(_ sender: XMPPRoster!, didReceiveRosterItem item: DDXMLElement!) {
        let rosterName = item.attributeStringValue(forName: "jid")
        let type = item.attributeStringValue(forName: "subscription")
        let ask = item.attributeStringValue(forName: "ask")
        
        //如果type为remove并且ask为nil 表明主动删除的好友
        if type == "remove" && ask == nil {
            onlineRosters.remove(rosterName!)
            offlineRosters.remove(rosterName!)
            self.tableview.reloadData()
            //如果type为remove 并且ask == subscribe,表明主动删除尝试添加的好友
        }else if type == "remove" && ask == "subscribe"{
        tryRosters.remove(rosterName!)
            self.tableview.reloadData()
        }
        
        
        //如果type为to，并且ask为nil，表明该好友被删除
        if type == "to" && ask == nil {
            
            onlineRosters.remove(rosterName!)
            offlineRosters.remove(rosterName!)
            self.tableview.reloadData()
        //如果type为none，并且asl为subscribe，表明尝试添加的好友
        }else if type == "none" && ask != nil  && ask == "subscribe"{
            //先判断有木有这个人，避免重复添加
            if !tryRosters.contains(rosterName!) {
                tryRosters.add(rosterName!)
                self.tableview.reloadData()
            }
        }
        
        //如果type 为both，并且ask为nil，表明已添加的好友
        if type == "both" && ask == nil {
            if tryRosters.contains(rosterName!) && !onlineRosters.contains(rosterName!) {
                //从尝试加的好友中删除该用户
                tryRosters.remove(rosterName!)
                onlineRosters.add(rosterName!)
                self.tableview.reloadData()
            }
            //并且该用户不是在线用户
            if !onlineRosters.contains(rosterName!) && !offlineRosters.contains(rosterName!){
                offlineRosters.add(rosterName!)
                self.tableview.reloadData()
            }
        }
    
    }
    //对方好友请求时激发的方法
    func xmppRoster(_ sender: XMPPRoster!, didReceivePresenceSubscriptionRequest presence: XMPPPresence!) {
        let presemceFromUser = presence.from().user + "@muxue.local"
        let JID = XMPPJID(string: presemceFromUser)
        let alert = UIAlertController(title: "好友请求", message: "您收到了来自\(presemceFromUser)的添加好友申请，是否同意添加?", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "是", style: .default, handler: { (title) in
            self.xmppRoster.acceptPresenceSubscriptionRequest(from: JID, andAddToRoster: true)
        }))
        
        alert.addAction(UIAlertAction(title: "否", style: .default, handler: { (ttile) in
            self.xmppRoster.rejectPresenceSubscriptionRequest(from: JID)
        }))
        
    }
    //获取万好友列表时激发该方法
    func xmppRosterDidEndPopulating(_ sender: XMPPRoster!) {
        
    }
    
}
